package cn.iocoder.ny.module.mall.controller.admin.config;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.crypto.PemUtil;
import cn.iocoder.ny.module.mall.annotation.Encrypt;
import cn.iocoder.ny.module.mall.domain.MallConfig;
import cn.iocoder.ny.module.mall.controller.admin.config.vo.MallConfigPageVo;
import cn.iocoder.ny.module.mall.service.IMallConfigService;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantChangeVO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.RoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantMapper;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;


/**
 * @author lc
 * @date 2024/07/23/ 11:44
 * @description:商城配置类
 */
@RestController
@RequestMapping("/config")
public class MallConfigController{

    @Autowired
    private IMallConfigService mallConfigService;
    @Resource
    private RoleService roleService;

    @Resource
    private RoleMapper roleMapper;
    /**
     * 新增商城配置
     */
    @RequestMapping("/addConfig")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin')")
    public CommonResult addConfig(@RequestBody @Validated({MallConfig.Add.class}) MallConfig mallConfig) {
        try {
            mallConfigService.addConfig(mallConfig);
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            return error(500,e.getMessage());
        }
    }

    @RequestMapping("getPrivateKey")
    @PermitAll
    public CommonResult getPrivateKey(@RequestBody MallConfig mallConfig)
    {
        return success(mallConfigService.getById(mallConfig.getTenantId()));
    }

    /**
     * 修改商城配置
     *
     */
    @RequestMapping("/updateConfig")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin')")
    public CommonResult<Boolean> updateConfig(@RequestBody @Validated({MallConfig.Update.class}) MallConfig mallConfig)
    {
        try {
            mallConfigService.updateConfig(mallConfig);
            return success(true);
        } catch (Exception e) {
            return error(500,e.getMessage());
        }
    }


    /**
     * 修改商城配置BySaas
     *
     */
    @RequestMapping("/updateConfigBySaas")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin')")
    public CommonResult<Boolean> updateConfigBySaas(@RequestBody @Validated({MallConfig.Update.class}) MallConfig mallConfig) {
        try {
            Boolean b = mallConfigService.updateConfigBySaas(mallConfig);
            if (b) {
                return success(true);
            }
            return error(500,"失败");
        } catch (RuntimeException e) {
            return error(500, e.getMessage());
        }
    }

    /**
     * 删除商城配置
     *
     */
    @RequestMapping("/deleteConfig")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin')")
    public CommonResult<Boolean> deleteConfig(@RequestBody @Validated({MallConfig.Del.class}) MallConfig mallConfig)
    {
        if (mallConfig.getId() != null){
            mallConfigService.removeById(mallConfig.getId());
        }
        // 把当前店铺下的角色删除
        // 查询出当前店铺下的商城商城核销员 跟商城核销员
       // 通过tenantId查询当前店铺下的所有Code
        Long tenantId = getLoginUser().getTenantId();

        RoleDO tenantRoleOpera = roleMapper.selectByCodeBytennatId("mall_operator",tenantId);
        RoleDO tenantRoleVerfica = roleMapper.selectByCodeBytennatId("mall_verification",tenantId);
        if (!ObjectUtils.isEmpty(tenantRoleOpera)){
            roleService.deleteRole(tenantRoleOpera.getId());
        }
        if (!ObjectUtils.isEmpty(tenantRoleVerfica)) {
            roleService.deleteRole(tenantRoleVerfica.getId());
        }
        return success(true);
    }
    /**
     * 根据TenatnId查询商城配置
     */
    @PostMapping("/getConfigByTenantId")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin')")
    public CommonResult getConfigByTenantId(@RequestBody MallConfig mallConfig)
    {
        Long tenantId = getLoginUser().getTenantId();
        MallConfig mallConfigSelect = mallConfigService.lambdaQuery().eq(MallConfig::getTenantId, tenantId).one();
        return success(mallConfigSelect);
    }


    /**
     * 根据id查询商城配置
     *
     */
    @RequestMapping("/getConfigById")
    @Encrypt
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin')")
    public CommonResult getConfigById(@RequestBody @Validated({MallConfig.Query.class}) MallConfig mallConfig)
    {
        return success(mallConfigService.getById(mallConfig.getId()));
    }

    /**
     * 分页查询商城配置 不传值默认查询全部
     */
    @RequestMapping("/getConfigList")
    @PermitAll
    public CommonResult<PageResult<MallConfig>>  getConfigList(@RequestBody MallConfigPageVo mallConfigPageVo)
    {
        PageResult<MallConfig> list = mallConfigService.getConfigPage(mallConfigPageVo);
        return success(list);
    }
    /**
     * 通过AppId来进行查询小程序二维码
     */
    /**
     * 查询出该用户所拥有的所有店铺
     */
    @PostMapping("/getTenantListByUser")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin')")
    public CommonResult<List<TenantDO>> getTenantListByUser(@RequestBody TenantChangeVO tenantChangeVO) {
        return success(mallConfigService.getTenantListByUser(tenantChangeVO.getUserName()));
    }

    /**
     * 获取当前店铺的信息
     */
    @PostMapping("/getConfigInfo")
    @PermitAll
    public CommonResult getConfigInfo(@RequestBody MallConfig mallConfig) {
        MallConfig mallConfigInfo = mallConfigService.lambdaQuery().eq(MallConfig::getTenantId, mallConfig.getTenantId()).one();
        Map<String, Object> mallMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(mallConfigInfo)){
            mallMap.put("tenantId",mallConfigInfo.getTenantId());
            mallMap.put("mallName",mallConfigInfo.getMallName());
            mallMap.put("mallMobile",mallConfigInfo.getMallMobile());
            mallMap.put("malIntroduce",mallConfigInfo.getMallIntroduce());
            //mallMap.put("mallAddress",mallConfigInfo.getMallAddress());
            mallMap.put("mallAvatar",mallConfigInfo.getMallAvatar());
        }
        return success(mallMap);
    }

}
